// incrementArray.cu
#include <stdio.h>
#include <assert.h>
#include <cuda.h>

void incrementArrayOnHost(float *a, int N)
{
  int i;
  for (i=0; i < N; i++) a[i] = a[i]+1.f;
}

__global__ void incrementArrayOnDevice(float *a, int N)
{
  int idx = blockIdx.x*blockDim.x + threadIdx.x;
  if (idx<N) a[idx] = a[idx]+1.f;
}

int main(void)
{
  printf("\nAllocate Static Memory");
  float *a_h, *b_h;           // pointers to host memory
  float *a_d;                 // pointer to device memory
  int i, N = 10;
  size_t size = N*sizeof(float);

  printf("\nAllocate array1 on host");
  a_h = (float *)malloc(size);
  printf("\nAllocate array2 on host");
  b_h = (float *)malloc(size); 
 
  printf("\ninitialization of host data");
  for (i=0; i<N; i++) a_h[i] = (float)i;
  
  printf("\nallocate array on device"); 
  cudaMalloc((void **) &a_d, size);

  printf("\ncopy data from host to device");
  cudaMemcpy(a_d, a_h, sizeof(float)*N, cudaMemcpyHostToDevice);

  printf("\ndo calculation on host");
  incrementArrayOnHost(a_h, N);

  // do calculation on device:
  printf("\nCompute execution configuration");
  int blockSize = 4;
  int nBlocks = N/blockSize + (N%blockSize == 0?0:1);
  
  printf("\nPart 2 of 2. Call incrementArrayOnDevice kernel"); 
  incrementArrayOnDevice <<< nBlocks, blockSize >>> (a_d, N);
 
  printf("\nRetrieve result from device and store in b_h");
  cudaMemcpy(b_h, a_d, sizeof(float)*N, cudaMemcpyDeviceToHost);
 
  printf("\ncheck results");
  for (i=0; i<N; i++) assert(a_h[i] == b_h[i]);
 
  printf("\ncleanup");
  free(a_h); free(b_h); cudaFree(a_d); 
}
